package com.jkgh.remedium.objects.messages;

import java.util.HashMap;

import com.jkgh.asin.buffers.DataConsumer;
import com.jkgh.remedium.RemediumConstants;
import com.jkgh.remedium.objects.RemediumObject;

public abstract class RemediumOutMessage {

	private final HashMap<RemediumObject, Integer> history;

	public RemediumOutMessage() {
		this.history = new HashMap<RemediumObject, Integer>();
	}
	
	public final void produce(DataConsumer consumer) {
		consumer.consumeByte(getRemediumMessageType());
		produceContent(consumer);
	}
	
	protected abstract void produceContent(DataConsumer consumer);
	protected abstract byte getRemediumMessageType();

	public void produceObject(RemediumObject object, DataConsumer consumer) {
		if (object == null) {
			consumer.consumeByte(RemediumConstants.NULL);
		} else {
			Integer ret = history.get(object);
			if (ret == null) {
				history.put(object, history.size());
				consumer.consumeByte(RemediumConstants.VALUE);
				object.produceContent(consumer, this);
			} else {
				consumer.consumeByte(RemediumConstants.HISTORY);
				consumer.consumeInt(ret);
			}
		}
	}
}
